package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	//TODO 如果捕获404
	fileServer := http.FileServer(http.Dir("./static"))
	http.Handle("/", StaticSiteHandle(fileServer))

	//http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
	//	fmt.Fprintf(w, "Hello Leo!")
	//})
	http.HandleFunc("/hello", helloHandler)

	//http.Handle("/sign", http.File("./static/form.html")) ?? 怎样指定一个文件
	http.HandleFunc("/form", formHandler)
	fmt.Printf("Starting server at port 8080\n")
	if err := http.ListenAndServe("localhost:8080", nil); err != nil {
		log.Fatal(err)
	}
}
func StaticSiteHandle(h http.Handler) http.Handler {
	log.Printf("%v", h)
	return h
	//return http.HandleFunc(helloHandler)
	//return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
	//	h.ServeHTTP(w, r)
	//})

}

func formHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Log: form")
	if err := r.ParseForm(); err != nil {
		fmt.Fprintf(w, "ParseForm() err:%v", err)
		return
	}
	fmt.Fprintf(w, "Post request successful")
	name := r.FormValue("name")
	address := r.FormValue("address")
	age := r.FormValue("age")
	fmt.Fprintf(w, "Name=%s\n Address = %s\n Age = %s\n", name, address, age)
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Log： hello")
	if r.URL.Path != "/hello" {
		http.Error(w, "404 not found.", http.StatusNotFound)
		return
	}

	if r.Method != "GET" {
		http.Error(w, "Method is not supported.", http.StatusNotFound)
		return
	}

	fmt.Fprintf(w, "Hello!")

}
